<template>
  <div class="order-management">
    <!-- 头部导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>会员中心</el-breadcrumb-item>
      <el-breadcrumb-item>订单管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="输入关键字进行搜索"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button icon="el-icon-search" @click="handleSearch"></el-button>
        </template>
      </el-input>
    </div>

    <!-- 布局容器 -->
    <div class="layout-container">
      <!-- 左侧菜单 -->
      <el-aside width="200px">
        <el-menu default-active="orders">
          <el-menu-item index="profile">账号管理</el-menu-item>
          <el-menu-item index="messages">消息通知</el-menu-item>
          <el-menu-item index="account">账号信息</el-menu-item>
          <el-menu-item index="address">地址管理</el-menu-item>
          <el-menu-item index="security">账号安全</el-menu-item>
          <el-menu-item index="points">我的积分</el-menu-item>
          <el-menu-item index="favorites">我的收藏</el-menu-item>
          <el-menu-item index="footprints">我的足迹</el-menu-item>
          <el-menu-item index="transactions">交易管理</el-menu-item>
          <el-menu-item index="orders">订单管理</el-menu-item>
          <el-menu-item index="coupons">优惠券</el-menu-item>
          <el-menu-item index="giftcards">礼品卡</el-menu-item>
          <el-menu-item index="service">服务中心</el-menu-item>
          <el-menu-item index="returns">售后记录</el-menu-item>
          <el-menu-item index="help">帮助中心</el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 右侧内容区 -->
      <el-main>
        <el-tabs v-model="activeTab" type="card" @tab-change="filterOrders">
          <el-tab-pane label="全部订单" name="all"></el-tab-pane>
          <el-tab-pane label="待付款" name="pendingPayment"></el-tab-pane>
          <el-tab-pane label="待发货" name="pendingShipping"></el-tab-pane>
          <el-tab-pane label="待收货" name="pendingReceipt"></el-tab-pane>
          <el-tab-pane label="待评价" name="pendingReview"></el-tab-pane>
        </el-tabs>

        <!-- 添加空状态提示 -->
        <el-empty v-if="filteredOrders.length === 0" description="暂无订单数据" />
        
        <el-table v-else :data="pagedOrders" style="width: 100%">
          <el-table-column prop="orderTime" label="下单时间" width="180"></el-table-column>
          <el-table-column prop="orderId" label="订单号" width="180"></el-table-column>
          <el-table-column label="商品信息">
            <template #default="scope">
              <!-- 添加空值检查 -->
              <div v-if="scope.row" class="product-info">
                <img 
                  :src="scope.row.productImage || 'https://via.placeholder.com/60'" 
                  alt="商品图片" 
                  class="product-image"
                >
                <div class="product-details">
                  <p>{{ scope.row.productName || '未命名商品' }}</p>
                  <small>
                    颜色：{{ scope.row.color || '默认' }} 
                    尺码：{{ scope.row.size || '均码' }} 
                    数量：{{ scope.row.quantity || 1 }}
                  </small>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row" :type="statusTagType(scope.row.status)">
                {{ statusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" label="金额" width="120">
            <template #default="scope">
              ¥{{ scope.row ? scope.row.totalPrice.toFixed(2) : '0.00' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <!-- 添加空值检查 -->
              <div v-if="scope.row">
                <el-button 
                  v-if="scope.row.status === 'pendingPayment'"
                  type="danger"
                  @click="handlePay(scope.row.id)"
                >付款 {{ formatRemainingTime(scope.row.remainingTime) }}</el-button>
                <el-button 
                  v-if="scope.row.status === 'pendingShipping'"
                  type="primary"
                  @click="handleConfirmReceipt(scope.row.id)"
                >确认收货</el-button>
                <el-button 
                  v-if="['pendingPayment', 'pendingShipping'].includes(scope.row.status)"
                  type="warning"
                  @click="handleCancelOrder(scope.row.id)"
                >取消订单</el-button>
                <el-button 
                  type="text"
                  @click="handleViewDetails(scope.row.id)"
                >查看详情</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <el-pagination
          v-if="filteredOrders.length > pageSize"
          class="pagination"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="filteredOrders.length"
          @current-change="handlePageChange"
        ></el-pagination>
      </el-main>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

const router = useRouter()
const activeTab = ref('all')
const allOrders = ref([])
const filteredOrders = ref([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 状态映射
const statusMap = {
  pendingPayment: '待付款',
  pendingShipping: '待发货',
  pendingReceipt: '待收货',
  pendingReview: '待评价',
  paid: '已付款',
  shipped: '已发货',
  received: '已收货',
  completed: '已完成',
  cancelled: '已取消'
}

// 状态标签类型
const statusTagType = (status) => {
  const types = {
    pendingPayment: 'danger',
    pendingShipping: 'warning',
    pendingReceipt: 'primary',
    pendingReview: 'info',
    paid: 'success',
    shipped: '',
    received: 'success',
    completed: 'success',
    cancelled: 'info'
  }
  return types[status] || ''
}

// 后端接口规范
const API_URLS = {
  GET_ORDERS: '/api/orders',
  PAY_ORDER: '/api/orders/:orderId/pay',
  CANCEL_ORDER: '/api/orders/:orderId/cancel',
  CONFIRM_RECEIPT: '/api/orders/:orderId/confirm-receipt',
  VIEW_DETAILS: '/api/orders/:orderId/details'
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    const response = await axios.get(API_URLS.GET_ORDERS)
    // 添加数据验证和默认值
    allOrders.value = response.data.map(o => ({
      id: o.id || Date.now().toString(),
      orderId: o.orderId || `ORDER_${Date.now()}`,
      orderTime: o.orderTime ? dayjs(o.orderTime).format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss'),
      productImage: o.productImage || 'https://via.placeholder.com/60',
      productName: o.productName || '未命名商品',
      color: o.color || '默认',
      size: o.size || '均码',
      quantity: o.quantity || 1,
      status: o.status || 'pendingPayment',
      totalPrice: o.totalPrice || 0,
      remainingTime: o.remainingTime || 1800 // 默认30分钟
    }))
    filterOrders()
  } catch (error) {
    console.error('获取订单失败:', error)
    ElMessage.error('获取订单数据失败')
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  filterOrders()
}

// 过滤订单
const filterOrders = () => {
  let result = [...allOrders.value]
  
  // 根据活动标签过滤
  if (activeTab.value !== 'all') {
    result = result.filter(o => o.status === activeTab.value)
  }
  
  // 根据关键字搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(o => 
      (o.orderId && o.orderId.toLowerCase().includes(keyword)) ||
      (o.productName && o.productName.toLowerCase().includes(keyword)
    ))
  }
  
  // 过滤掉无效数据
  result = result.filter(item => item != null)
  
  filteredOrders.value = result
}

// 支付订单
const handlePay = async (orderId) => {
  try {
    await axios.post(API_URLS.PAY_ORDER.replace(':orderId', orderId))
    const order = allOrders.value.find(o => o.id === orderId)
    if (order) {
      order.status = 'paid'
      filterOrders()
      ElMessage.success('支付成功')
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请重试')
  }
}

// 取消订单
const handleCancelOrder = async (orderId) => {
  try {
    await axios.delete(API_URLS.CANCEL_ORDER.replace(':orderId', orderId))
    allOrders.value = allOrders.value.filter(o => o.id !== orderId)
    filterOrders()
    ElMessage.success('订单已取消')
  } catch (error) {
    console.error('取消失败:', error)
    ElMessage.error('取消订单失败')
  }
}

// 确认收货
const handleConfirmReceipt = async (orderId) => {
  try {
    await axios.put(API_URLS.CONFIRM_RECEIPT.replace(':orderId', orderId))
    const order = allOrders.value.find(o => o.id === orderId)
    if (order) {
      order.status = 'received'
      filterOrders()
      ElMessage.success('确认收货成功')
    }
  } catch (error) {
    console.error('确认失败:', error)
    ElMessage.error('确认收货失败')
  }
}

// 查看详情
const handleViewDetails = (orderId) => {
  router.push({ name: 'OrderDetails', params: { id: orderId } })
}

// 状态文本转换
const statusText = (status) => {
  return statusMap[status] || status
}

// 格式化剩余时间
const formatRemainingTime = (seconds) => {
  if (!seconds) return ''
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
}

// 当前页显示的订单
const pagedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredOrders.value.slice(start, end)
})

onMounted(fetchOrders)
</script>

<style scoped>
.order-management {
  display: flex;
  flex-direction: column;
  padding: 20px;
  position: relative;
  min-height: 100vh;
}

.search-bar {
  margin: 20px 0;
  width: 400px;
  z-index: 10;
}

.layout-container {
  display: flex;
  margin-top: 20px;
}

.el-aside {
  width: 200px;
  min-height: 600px;
  overflow-y: auto;
  border-right: 1px solid #e6e6e6;
  background-color: #f8f8f8;
}

.el-main {
  flex: 1;
  padding: 0 20px 20px 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-left: 20px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #eee;
}

.product-details {
  display: flex;
  flex-direction: column;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-tabs {
  margin-bottom: 20px;
}

.el-table {
  margin-bottom: 20px;
}
</style>